package com.server.modules.api.service.impl;

import com.server.common.utils.PathUtils;
import com.server.common.utils.StringUtils;
import com.server.modules.api.service.IMService;
import com.server.modules.api.service.IUsedCarEvaluateService;
import com.server.modules.api.service.MemberAPIService;
import com.server.modules.api.vo.BaseQueryVo;
import com.server.modules.sys.entity.juhe.usedcar.*;
import com.server.modules.sys.entity.member.Member;
import com.server.modules.sys.service.juhe.usedcar.*;
import com.server.modules.sys.utils.FreeMarkerUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by Administrator on 2017/1/4.
 */
@Service
public class UsedCarEvaluateServiceImpl implements IUsedCarEvaluateService {
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 3000000;
    public static final int DEF_READ_TIMEOUT = 3000000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    //配置您申请的KEY
    public static final String APPKEY ="504e2cd050a9b3d43c9fa994f32d02ed";

    @Resource
    private MemberAPIService memberAPIService;
    @Resource
    private IMService imService;
    @Resource
    private JuheUsedcarProvinceService juheUsedcarProvinceService;

    @Resource
    private JuheUsedcarCityService juheUsedcarCityService;

    @Resource
    private JuheUsedcarBrandService juheUsedcarBrandService;

    @Resource
    private JuheUsedcarSeriesService juheUsedcarSeriesService;

    @Resource
    private JuheUsedcarModelService juheUsedcarModelService;

    @Resource
    private JuheUsedcarModelYearService juheUsedcarModelYearService;

    @Override
    public List<JuheUsedcarProvince> getAllProvince() {
        List<JuheUsedcarProvince> list = juheUsedcarProvinceService.findList(new JuheUsedcarProvince());
        if(CollectionUtils.isEmpty(list)){
            return  this.syncAllProvince();
        }
        return list;
    }

    @Override
    public  List<JuheUsedcarProvince> syncAllProvince() {
        List<JuheUsedcarProvince> list=new ArrayList<>();
        String result =null;
        String url ="http://v.juhe.cn/usedcar/province";//请求接口地址
        Map params = new HashMap();//请求参数
        params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
        try {
            result =net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);
            if(object.getInt("error_code")==0){
                System.out.println(object.get("result"));
                JSONArray result1 = object.getJSONArray("result");
                if(result1!=null&&result1.size()>0){
                    for (int i=0;i<result1.size();i++) {
                        JSONObject jsonObject = result1.getJSONObject(i);
                        if (jsonObject != null) {
                            JuheUsedcarProvince obj = new JuheUsedcarProvince();
                            String proID = jsonObject.getString("proID");/*省份的编码*/
                            String proName = jsonObject.getString("proName");  /*省份的名称*/
                            String pinyin = jsonObject.getString("pinyin");/*省份的名称拼音*/
                            String pin = jsonObject.getString("pin");/*省份的首字母*/
                            String hits = jsonObject.getString("hits");/*省份的首字母*/
                            obj.setId(proID);
                            obj.setName(proName);
                            obj.setPin(pin);
                            obj.setPinyin(pinyin);
                            obj.setHits(hits);
                            list.add(obj);
                        }
                    }
                }

            }else{
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        juheUsedcarProvinceService.saveAllProvince(list);
        return list;
    }

    @Override
    //1.城市列表
    public List<JuheUsedcarCity> getCityByProvince(String provinceId){
        if(StringUtils.isBlank(provinceId)){
            return null;
        }
        //先去数据库里面拉
        JuheUsedcarCity query=new JuheUsedcarCity();
        query.setProvinceId(provinceId+"");
        List<JuheUsedcarCity> list = juheUsedcarCityService.findList(query);
        if(CollectionUtils.isEmpty(list)){
            String result =null;
            String url ="http://v.juhe.cn/usedcar/city";//请求接口地址
            Map params = new HashMap();//请求参数
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
            params.put("province",provinceId);//返回数据的格式,xml或json，默认json
            try {
                result =net(url, params, "GET");
                System.out.println("去聚合取城市数据，省份id："+provinceId);
                JSONObject object = JSONObject.fromObject(result);
                if(object.getInt("error_code")==0){
                    System.out.println("去聚合取城市数据成功，数据为："+object.get("result"));
                    JSONArray result1 = object.getJSONArray("result");
                    if(result1!=null&&result1.size()>0){
                        for (int i=0;i<result1.size();i++) {
                            JSONObject jsonObject = result1.getJSONObject(i);
                            if (jsonObject != null) {
                                JuheUsedcarCity obj = new JuheUsedcarCity();
                                String cityID = jsonObject.getString("cityID"); /*城市id*/
                                String cityName = jsonObject.getString("cityName");   /*城市名称*/
                                String pinyin = jsonObject.getString("pinyin");/*城市名称拼音*/
                                String proID = jsonObject.getString("proID");/*省份id*/
                                String hits = jsonObject.getString("hits");
                                String area = jsonObject.getString("area");
                                obj.setId(cityID);
                                obj.setName(cityName);
                                obj.setPinyin(pinyin);
                                obj.setHits(hits);
                                obj.setProvinceId(proID);
                                obj.setArea(area);
                                list.add(obj);
                            }
                        }
                    }
                    //入库操作
                    juheUsedcarCityService.saveCitys(list);
                    return  list;
                }else{
                    System.out.println("去聚合取城市数据失败，"+object.get("error_code")+":"+object.get("reason"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return list;

    }
    @Override
    //2.品牌列表
    public List<JuheUsedcarBrand> getCarBrandList(String vehicle){
        if(StringUtils.isBlank(vehicle)){
            return null;
        }
        JuheUsedcarBrand query=new JuheUsedcarBrand();
        query.setVehicle(vehicle);
        List<JuheUsedcarBrand> list= juheUsedcarBrandService.findList(query);
        if(CollectionUtils.isEmpty(list)){
            String result =null;
            String url ="http://v.juhe.cn/usedcar/brand";//请求接口地址
            Map params = new HashMap();//请求参数
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
            params.put("vehicle",vehicle);//	车辆类型：passenger(乘用车)/commercial(商用车)
            try {
                result =net(url, params, "GET");
                System.out.println("去聚合取车辆品牌，vehicle："+vehicle);
                JSONObject object = JSONObject.fromObject(result);
                if(object.getInt("error_code")==0){
                    System.out.println("去聚合取车辆品牌成功："+object.get("result"));
                    JSONObject result1 = object.getJSONObject("result");
                   Iterator it = result1.keys();
                    while (it.hasNext()) {
                        String key = (String) it.next();
                        JSONArray array = result1.getJSONArray(key);
                        for(int i=0;i<array.size();i++){
                            JSONObject jsonobject = array.getJSONObject(i);
                            if (jsonobject != null) {
                                JuheUsedcarBrand obj = new JuheUsedcarBrand();
                                String id = jsonobject.getString("id");/*品牌id*/
                                String big_ppname = jsonobject.getString("big_ppname");   /*品牌名称*/
                                String pin = jsonobject.getString("pin");/*品牌首字母*/
                                obj.setId(id);
                                obj.setVehicle(vehicle);
                                obj.setName(big_ppname);
                                obj.setPin(pin);
                                list.add(obj);
                            }
                        }
                    }
                    if(!CollectionUtils.isEmpty(list)){
                      juheUsedcarBrandService.saveCarBrands(list);
                    }
                    return list;

                }else{
                    System.out.println("去聚合取车辆品牌失败："+object.get("error_code")+":"+object.get("reason"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }



    @Override
    //3.车系列表
    public List<JuheUsedcarSeries> getCarSeriesList(String brandId){
        if(StringUtils.isBlank(brandId)){
            return null;
        }
        //先去数据库里面拉
        JuheUsedcarSeries query=new JuheUsedcarSeries();
        query.setBrandId(brandId+"");
        List<JuheUsedcarSeries> list = juheUsedcarSeriesService.findList(query);
        if(CollectionUtils.isEmpty(list)){
            String result =null;
            String url ="http://v.juhe.cn/usedcar/series";//请求接口地址
            Map params = new HashMap();//请求参数
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
            params.put("brand",brandId);//返回数据的格式,xml或json，默认json
            try {
                result =net(url, params, "GET");
                System.out.println("去聚合取车系数据，品牌id："+brandId);
                JSONObject object = JSONObject.fromObject(result);
                if(object.getInt("error_code")==0){
                    System.out.println("去聚合取车系数据成功，数据为："+object.get("result"));
                    JSONObject result1 = object.getJSONObject("result");
                    if(result1!=null){
                        JSONArray pinpai_list = result1.getJSONArray("pinpai_list");
                        for(int i=0;i<pinpai_list.size();i++){
                            JSONObject jsonobject = pinpai_list.getJSONObject(i);
                            if (jsonobject != null) {
                               // String ppid = jsonobject.getString("ppid");/*品牌id*/
                                String ppname = jsonobject.getString("ppname");   /*品牌名称*/
                                JSONArray xilies = jsonobject.getJSONArray("xilie");
                                for(int j=0;j<xilies.size();j++){
                                    JSONObject objjson = xilies.getJSONObject(j);
                                    JuheUsedcarSeries obj=new JuheUsedcarSeries();
                                    String xlname = objjson.getString("xlname");
                                    String xlid = objjson.getString("xlid");
                                    obj.setPpname(ppname);
                                    obj.setBrandId(brandId);
                                    obj.setName(xlname);
                                    obj.setId(xlid);
                                    list.add(obj);
                                }
                            }
                        }
                    }
                    //入库操作
                    juheUsedcarSeriesService.saveSeriess(list);
                    return  list;
                }else{
                    System.out.println("去聚合取车系数据失败，"+object.get("error_code")+":"+object.get("reason"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return list;

    }
    @Override
    //4.车型列表
    public List<JuheUsedcarModel> getCarModelList(String seriesId){
        if(StringUtils.isBlank(seriesId)){
            return null;
        }
        //先去数据库里面拉
        JuheUsedcarModel query=new JuheUsedcarModel();
        query.setSeriesId(seriesId+"");
        List<JuheUsedcarModel> list = juheUsedcarModelService.findList(query);
        if(CollectionUtils.isEmpty(list)){
            String result =null;
            String url ="http://v.juhe.cn/usedcar/car";//请求接口地址
            Map params = new HashMap();//请求参数
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
            params.put("series",seriesId);//车系标识，可以通过车三百车系数据接口拿回车系信息，从而提前车系标识。
            try {
                result =net(url, params, "GET");
                System.out.println("去聚合取车辆型号数据，车系id："+seriesId);
                JSONObject object = JSONObject.fromObject(result);
                if(object.getInt("error_code")==0){
                    System.out.println("去聚合取车辆型号数据成功，数据为："+object.get("result"));
                    JSONObject result1 = object.getJSONObject("result");
                    JSONArray data = result1.getJSONArray("data");
                    for(int i=0;i<data.size();i++){
                        JSONObject jsonobject = data.getJSONObject(i);
                        String tyear = jsonobject.getString("pyear");
                        JSONArray chexing_list = jsonobject.getJSONArray("chexing_list");
                        for(int j=0;j<chexing_list.size();j++){
                            JSONObject objjson = chexing_list.getJSONObject(j);
                            JuheUsedcarModel obj=new JuheUsedcarModel();
                            String id = objjson.getString("id");
                            String cxname = objjson.getString("cxname");
                            String ppyear = objjson.getString("pyear");
                            String price = objjson.getString("price");
                            obj.setId(id);
                            obj.setName(cxname);
                            obj.setSeriesId(seriesId);
                            obj.setPrice(price);
                            obj.setYear(ppyear);
                            obj.setTyear(tyear);
                            list.add(obj);
                        }
                    }

                    //入库操作
                    juheUsedcarModelService.saveModels(list);
                    return  list;
                }else{
                    System.out.println("去聚合取车辆型号数据失败，"+object.get("error_code")+":"+object.get("reason"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;



    }

    @Override
    //4.车型列表
    public List<JuheUsedcarModelYear> getCarYearList(String carId){
        if(StringUtils.isBlank(carId)){
            return null;
        }
        //先去数据库里面拉
        JuheUsedcarModelYear query=new JuheUsedcarModelYear();
        query.setModelId(carId);
        List<JuheUsedcarModelYear> list = juheUsedcarModelYearService.findList(query);
        if(CollectionUtils.isEmpty(list)){
            String result =null;
            String url ="http://v.juhe.cn/usedcar/year";//请求接口地址
            Map params = new HashMap();//请求参数
            params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
            params.put("car",carId);//车系标识，可以通过车三百车系数据接口拿回车系信息，从而提前车系标识。
            try {
                result =net(url, params, "GET");
                System.out.println("去聚合取车型年份数据，省份id："+carId);
                JSONObject object = JSONObject.fromObject(result);
                if(object.getInt("error_code")==0){
                    System.out.println("去聚合取车型年份数据成功，数据为："+object.get("result"));
                    JSONArray result1 = object.getJSONArray("result");
                    if(result1!=null&&result1.size()>0){
                        for (int i=0;i<result1.size();i++) {
                            String year = result1.getString(i);
                            JuheUsedcarModelYear obj=new JuheUsedcarModelYear();
                            obj.setYear(year);
                            obj.setModelId(carId);
                            list.add(obj);
                        }
                    }
                    //入库操作
                    juheUsedcarModelYearService.saveModelYears(list);
                    return  list;
                }else{
                    System.out.println("去聚合取车型年份数据失败，"+object.get("error_code")+":"+object.get("reason"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }


    @Override
    //7.精确估值
    public Map doEvaluation( String provinceId, String cityId, String carId, String useddate, String useddateMonth, Integer mileage, Integer price, HttpServletRequest request, BaseQueryVo vo){
        String carstatus="2";
        Integer purpose=1;
        if(StringUtils.isBlank(carstatus)||purpose==null||StringUtils.isBlank(provinceId)||StringUtils.isBlank(cityId)||StringUtils.isBlank(carId)||StringUtils.isBlank(useddate)||StringUtils.isBlank(useddateMonth)||mileage==null||price==null){
                return null;
        }
        Map ret=new HashedMap();
        ret.put("succeed",false);
        String fileName=carstatus+"_"+purpose+"_"+provinceId+"_"+cityId+"_"+carId+"_"+useddate+"_"+useddateMonth+"_"+mileage+"_"+price;//组成key
        //看缓存命中没
        String outFileName= PathUtils.getPropertiesKeyValue("application.properties","static.html.path")+ File.separator+fileName+".html";
        File file=new File(outFileName);
        Member member = memberAPIService.get(new Member(vo.getMemberId()));
        if(member==null){
            ret.put("succeed",false);
            ret.put("msg","查询估值信息申请失败");
            return ret;
        }
        if(file.exists()){
            System.out.println("【"+outFileName+"】静态页面命中");
            List<String> userList = new ArrayList<String>(1);
                userList.add(member.getHxUsername());
                Map<String,String > msg = new HashedMap();
                msg.put("type","text");
                StringBuffer bf=new StringBuffer("您申请的二手车估值信息查询成功！");
                msg.put("msg",bf.toString());
                Map<String,String > ext = new HashedMap();
                String link=PathUtils.getPropertiesKeyValue("application.properties","static.html.serverpath")+"/evaluation/"+fileName+".html";
                ext.put("data",link);
                ext.put("type","4");//1为产品，2为申请记录 3链接
                imService.sendSysMessages(userList,msg,ext);
                ret.put("succeed",true);
                ret.put("msg","查询估值信息申请成功，系统稍后会为您发送查询结果");
            return ret;
        }

        Map data=new HashedMap();
        String result =null;
        String url ="http://v.juhe.cn/usedcar/assess";//请求接口地址
        Map params = new HashMap();//请求参数
        params.put("key",APPKEY);//应用APPKEY(应用详细页查询)
        params.put("carstatus",carstatus);//是	车况，较差3，一般2，优秀1
        params.put("purpose",purpose);//车辆用途: 1自用 2公务商用 3营运
        params.put("province",provinceId);//省份标识（从“二手车价值评估/省份列表”接口获取)
        params.put("city",cityId);//城市标识（从“二手车价值评估/城市列表”接口获取)
        params.put("car",carId);//车型标识（从“二手车价值评估/车型列表”接口获取)
        params.put("useddate",useddate);//待估车辆的启用年份（格式：yyyy）
        params.put("useddateMonth",useddateMonth);//待估车辆的启用月份（格式：mm）
        params.put("mileage",mileage);//待估车辆的公里数，单位万公里
        params.put("price",price);//待估车辆在购买价(单位万元)
        try {
            result =net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);
            if(object.getInt("error_code")==0){
                System.out.println(object.get("result"));
                JSONObject result1 = object.getJSONObject("result");
                JSONArray est_price_result = result1.getJSONArray("est_price_result");
                JSONArray est_price_area = result1.getJSONArray("est_price_area");
                String acquirePrice="0";//收购价格
                String personalTradingPrice="0";//
                String saledPrice="0";//卖出价格
                if(est_price_result!=null&&est_price_result.size()>0){
                    //收购价格 个人交易价格 卖出价格
                    for (int i=0;i<est_price_result.size();i++) {
                        if(i==0){// 收购价格
                            acquirePrice=est_price_result.getString(i);
                        }
                        if(i==1){// 个人交易价格
                            personalTradingPrice=est_price_result.getString(i);
                        }
                        if(i==2){ // 卖出价格
                            saledPrice=est_price_result.getString(i);
                        }
                    }
                }
                data.put("acquirePrice",acquirePrice);
                data.put("personalTradingPrice",personalTradingPrice);
                data.put("saledPrice",saledPrice);
                if(est_price_area!=null&&est_price_area.size()>0){
                    List<Map> list=new ArrayList<>();
                    data.put("priceArea",list);
                    //各地区的价格
                    for (int i=0;i<est_price_area.size();i++) {
                        Map obj=new HashedMap();
                        JSONObject jsonObject = est_price_area.getJSONObject(i);
                        String price1 = jsonObject.getString("price");
                        String area = jsonObject.getString("area");
                        String areaid = jsonObject.getString("areaid");
                        obj.put("price",price1);
                        obj.put("area",area);
                        obj.put("areaid",areaid);
                        list.add(obj);
                    }
                }
            }else{
                System.out.println(object.get("error_code")+":"+object.get("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 初始化模板引擎
        FreeMarkerUtils.initFreeMarker(request.getSession().getServletContext().getRealPath("") );
        //生成静态页面成功
       if(FreeMarkerUtils.crateFile(data, "template/api/juhe/template_evaldetail.html", outFileName, true)){
           List<String> userList = new ArrayList<String>(1);
               userList.add(member.getHxUsername());
               Map<String,String > msg = new HashedMap();
               msg.put("type","text");
               StringBuffer bf=new StringBuffer("您申请的二手车估值信息查询成功！");
               msg.put("msg",bf.toString());
               Map<String,String > ext = new HashedMap();
               String link=PathUtils.getPropertiesKeyValue("application.properties","static.html.serverpath")+"/evaluation/"+fileName+".html";
               ext.put("data",link);
               ext.put("type","4");//1为产品，2为申请记录  3资料不全 4.链接
               imService.sendSysMessages(userList,msg,ext);
               ret.put("succeed",true);
               ret.put("msg","查询估值信息申请成功，系统稍后会为您发送查询结果");
           return ret;
       }
        return ret;
    }






    /**
     *
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return  网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, Map params,String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    //将map型转为请求参数型
    public static String urlencode(Map<String,Object>data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
